<?php

require_once app_path().'/pay/dysms/Sms.php';

use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Auth;
class UserController  extends BaseController {
	
	protected $layout = 'layouts.front';
	
	public function getProvinces(){
		$provinces = Province::all();
		$pid = Input::get("pid",$provinces->first()->id);
		$cities = City::where('province_id','=',$pid)->get();
		
		$cid = Input::get('cid',$cities->first()->id);
		$districts =  District::where('city_id','=',$cid)->get();
		return Response::json(array("provinces"=>$provinces,"cities" => $cities,"districts" => $districts));
	}
	public function getCities($id){
		$cities = City::where('province_id','=',$id)->get();
		$districts =  District::where('city_id','=',$cities->first()->id)->get();
		
		return Response::json(array("cities"=>$cities,"districts"=>$districts));
	}
	
	public function getDistricts($id){
		$districts = District::where('city_id','=',$id)->get();
		return Response::json($districts);
	}
	
	
	
	
	public function postUserAddress(){
		$data = Input::all();
		
		$data = Input::all();
		$validator = Validator::make(
				$data,
				array(
						'name' => 'required|max:32',
						'mobile'=> 'required|numeric',
						'zipcode' => 'max:16',
						'province_id'=>'required|numeric|min:1',
						'city_id'=>'required|numeric|min:1',
						'district_id'=>'required|numeric|min:1',
						'street'=>'required|max:256',
				),
				array(
						'required' =>'%s不能为空',
						'max'=>'%s不能超过:max字符',
				)
		);
		if ($validator->fails()){
			return array('success'=>false,'errors'=>$validator->messages());
		} else {
			//如果Id为空则是添加
			if (empty($data['id'])){
				$province = Province::find($data['province_id']);
				$city = City::find($data['city_id']);
				$district = District::find($data['district_id']);
				$data['user_id'] = Auth::id();
				$data['default'] = 0;
				$data['province'] = $province->name;
				$data['city'] = $city->name;
				$data['district'] = $district->name;
				$address = UserAddress::create($data);
				$data['id'] = $address->id;
			} else {
				$address = UserAddress::find($data['id']);
				$province = Province::find($data['province_id']);
				$city = City::find($data['city_id']);
				$district = District::find($data['district_id']);
				$data['province'] = $province->name;
				$data['city'] = $city->name;
				$data['district'] = $district->name;
				$address->update($data);
			}
			
			$data['success'] = true;
			return $data;
		}
	}
	
	public function checkOrderQuantity(){
		//1.获取产品数据
		$productCookie = $_COOKIE['cart_maggiemaostudio'];
		if (empty($productCookie)){
			return array('success'=>false,'errors'=>array('products'=>'没有商品'));
		}
		//产品列表
		$products = json_decode($productCookie,true);
		
		//需要检查库存
		$quantityCheckResult = $this->checkQuantitiy($products);
		
		//如果库存不够，则直接返回，提示用户
		if (!empty($quantityCheckResult)){
			return Response::json(array('success' => false,'error_no' => '1','errors'=>$quantityCheckResult));
		} else {
			return Response::json(array('success' => true));
		}
		 
	}
	
	private function checkQuantitiy($products){
		$quantityCheckResult = array();
		foreach($products as $p){
			$quantity = $p['quantity'];
			$productId = $p['id'];
			$size_id = array_get($p, 'size_id',0);
			$color_id = array_get($p, 'color_id',0);
			if (!empty($size_id)){
				$size = ProductSizes::find($size_id);
				$current_quantity = 0;
				if (!empty ($size)){
					$current_quantity = $size->quantity;
				}
				if ($current_quantity < $quantity){
					$quantityCheckResult[] = array('product_id'=>$productId,'size_id'=>$size_id,'current_quantity'=>$current_quantity,'quantity'=>$quantity);
				}
			} else if (!empty($color_id)){
				$color = ProductColors::find($color_id);
				$current_quantity = 0;
				if (!empty ($color)){
					$current_quantity = $color->quantity;
				}
				if ($current_quantity < $quantity){
					$quantityCheckResult[] = array('product_id'=>$productId,'color_id'=>$color_id,'current_quantity'=>$current_quantity,'quantity'=>$quantity);
				}
			} else {
				$product = Products::find($productId);
				$current_quantity = 0;
				if (!empty ($product)){
					$current_quantity = $product->quantity;
				}
				if ($current_quantity < $quantity){
					$quantityCheckResult[] = array('product_id'=>$productId,'current_quantity'=>$current_quantity,'quantity'=>$quantity);
				}
			}
		}
		return $quantityCheckResult;
	}
	
	public function postOrder(){
		
// 		1.验证是否选择送货地址
// 		2.如果寄送卡片，是否填写了卡片内容，是否超出了100个字
// 		3.给卖家留言是否出100个字
// 		4.产品是否为空
// 		5.csrf

		$data = Input::all();
		$validator = Validator::make(
				$data,
				array(
						'leave_message' => 'max:100',
						'user_address_id'=> 'required',
						'card_type' => 'required',
						'card_content'=>'required_if:card_type,3|max:100',
				)
		);
		if ($validator->fails()){
			return array('success'=>false,'errors'=>$validator->messages());
		}

		//1.获取产品数据
		$productCookie = $_COOKIE['cart_maggiemaostudio'];
		if (empty($productCookie)){
			return array('success'=>false,'errors'=>array('products'=>'没有商品'));
		}
		//避免前段textarea为空的时候没有该字段
		if (empty($data["leave_message"])){
			$data["leave_message"] = "";
		}
		if (empty($data["card_content"])){
			$data["card_content"] = "";
		}

		//设置终端类型
		if ($this->isMobile()){
			$data["terminal_type"] = 2;
		} else {
			//电脑端
			$data["terminal_type"] = 1;
		}

		//产品列表
		$products = json_decode($productCookie,true);
		//保存产品列表
		$orderProducts = array();

		foreach($products as $p){
			$orderProducts[] = new OrderProduct(array(
					'product_id' => $p['id'],
					'quantity'   => $p['quantity'],
					'price'      => $p['price'],
					'size_id'    => array_get($p, 'size_id',0),
					'size'       => array_get($p, 'size',""),
					'color_id'   => array_get($p, 'color_id',0),
					'color'      => array_get($p, 'color',"")
			));
		}



		$order = DB::transaction(function() use ($data,$products,$orderProducts){
			//需要检查库存
			$quantityCheckResult = $this->checkQuantitiy($products);

			//如果库存不够，则直接返回，提示用户
			if (!empty($quantityCheckResult)){
				return array('success' => false,'error_no' => '1','errors'=>$quantityCheckResult);
			}
			//计算运费，产品总价
			$product_total_price = 0;
			foreach ($products as $p){
				$product_total_price += $p['price'] * $p['quantity'];
			}

			//超出1000元则免费
			$freight = Config::get("mao.postage");//默认15快运费
			if ($product_total_price >= Config::get("mao.free_postage_limit")){
				$freight = 0;
			} else {
				//计算产品中是否有免邮产品,如果有免邮产品则全部免邮
				$productIds = array();
				foreach ($products as $p){
					$productIds[] = $p['id'];
				}
				$dbProducts = Products::whereIn("id",$productIds)->get();
				foreach($dbProducts as $p){
					if ($p->postage_mode == 2){
						$freight = 0;
						break;
					}
				}
			}


			$user = Auth::user();

			$orderData = array(
					'user_id' => $user->id,
					'user_name' => $user->name,
					'product_total_price' => $product_total_price,
					'freight' => $freight,
					'leave_message' => $data['leave_message'],
					'user_address_id' => $data['user_address_id'],
					'status' => 0,
					'terminal_type' => $data['terminal_type']
			);
			$order = Order::create($orderData);

			//保存订单和产品的关系
			$order->products()->saveMany($orderProducts);

			//保存card信息
			//我需要一张空卡片
			if ($data['card_type'] == 2){
				$orderCard = new OrderCard(array('content'=>'我需要一张空白卡片'));
				$order->card()->save($orderCard);
			} else if ($data['card_type'] == 3){
				$orderCard = new OrderCard(array('content'=>$data['card_content']));
				$order->card()->save($orderCard);
			}

			//还需要减去商品的数量
			$productQuantities = array();
			foreach($products as $p){
				$quantity = $p['quantity'];
				$productId = $p['id'];
				$size_id = array_get($p, 'size_id',0);
				$color_id = array_get($p, 'color_id',0);
				if (!empty($size_id)){
					ProductSizes::where('id','=',$size_id)->decrement('quantity',$quantity);
				} else if (!empty($color_id)){
					ProductColors::where('id','=',$color_id)->decrement('quantity');
				}

				//累加同一商品的数量
				if (array_get($productQuantities,$productId,0) == 0){
					$productQuantities = array_add($productQuantities,$productId,$quantity);
				} else {
					$productQuantities = array_set($productQuantities,$productId,array_get($productQuantities,$productId,0) + $quantity);
				}
			}
			foreach($productQuantities as $key => $value){
				Products::where('id','=',$key)->decrement('quantity',$value);
			}
			return $order;
		});

		//如果库存不足，需要提示
		if (array_key_exists("success", $order)){
			return Response::json($order);
		}

		//发送订单邮件
		$user = Auth::user();
		$address = $order->address;
		$data = array(
				'id'=>$order->id,
				'total_fee'=>($order->freight+$order->product_total_price),
				'freight'=>$order->freight,
				'product_fee'=>$order->product_total_price,
				'user_name'=>$user->name,
				'express_id'=>$order->express_id,
				'express_name'=>$order->express_name,
				'address_name' => $address->name,
				'province'=>$address->province,
				'city'=>$address->city,
				'district' => $address->district,
				'street' =>$address->street,
				'zipcode'=>$address->zipcode,
				'mobile'=>$address->mobile,
				'card_content'=>$data['card_content']
		);

		$pids = array();
		foreach ($orderProducts as $op){
			$pids[] = $op->product_id;
		}
		//查询出产品信息
		$productInfos = Products::whereIn("id",$pids)->get();
		$productInfos->each(function($p) use (&$orderProducts){
			foreach($orderProducts as $op){
				if ($op["product_id"] == $p->id){
					$op["brand"] = $p->brand;
					$op["name"] = $p->name;
					$op["enname"] = $p->enname;
				}
			}
		});
		$data["orderProducts"] = $orderProducts;
// 		//图片，产品名称，商标关联等
// 		Mail::queue('emails.order_success', $data, function($message) use ($user){
// 			$message->to($user->email, $user->name)->subject('订单确认');
// 		});
		$config = Config::get("mao.sms.config");
		$sms = new Sms($config);
		$templateCode = Config::get("mao.sms.order");
		$param = array(
			'orderNo' => $order->id . ""
		);
		$sms->send($user->mobile,$templateCode,$param);
		return Response::json(array('success' => true,'order_id'=>$order->id));
	}
	
	public function showUser(){
		$content = $this->makeView('front.user.user');
		$this->layout->content = $content;
		$id = Auth::id();
		$user = User::find($id);
		$content->with("user",$user);
	}
	
	public function unbind(){
		$id = Auth::id();
		$user = User::find($id);
		$user->open_id = null;
		$user->save();
		return array('success'=>true);
	}
	
	public function showUserOrders(){
		$content = $this->makeView('front.user.order-list');
		$this->layout->content = $content;
		
		$id = Auth::id();
		$orders = Order::orderBy("id","desc")->where('user_id','=',$id)->paginate(50);
		$content->with("orders",$orders);
		
		
	}
	
	public function showUserOrderDetail($id){
		$content = $this->makeView('front.user.order-detail');
		$this->layout->content = $content;
		$order = Order::with("address","card")->with(array("products.product"=>function($query){
			$query->withTrashed();
		}))->find($id);
		$content->with("order",$order);
	}
	
	public function showUserAddresses(){
		$content = $this->makeView('front.user.address-list');
		$this->layout->content = $content;
		$id = Auth::id();
		$addresses = UserAddress::where('user_id','=',$id)->get();
		$content->with('addresses',$addresses);
	}
	
	public function deleteUserAddress(){
		$id = Input::get('id',0);
		if (empty($id)){
			return Response::json(array('success'=>false));
		}
		UserAddress::destroy($id);
		return Response::json(array('success'=>true));
	}
	
	public function showUserInfo(){
		$content = $this->makeView('front.user.userinfo');
		$this->layout->content = $content;
		$id = Auth::id();
		$user = User::find($id);
		$content->with("user",$user);
	}
	
	public function updateUserInfo(){
		$data = Input::all();
		$id = Auth::id();
		$validator = Validator::make(
				$data,
				array(
						'name' => 'required|max:32',
						'mobile'=> 'required|numeric',
						'email' => 'required | email|unique:users,email,'.$id,
				),
				array(
						'name.required' =>'姓名不能为空',
						'name.max'=>'姓名不能超过:max字符',
						'mobile.required'=>'手机不能为空',
						'mobile.numeric' =>'手机号不能存在数字以外的字符',
						'email.required' => '邮箱不能为空',
						'email.email' => '邮箱格式不正确',
						'email.unique' => '邮箱已经注册过',
				)
		);
		if ($validator->fails()){
			return array('success'=>false,'errors'=>$validator->messages());
		} else {
			User::find($id)->update($data);
			return array('success'=>true);
		}
	}
	
	public function showUserFavorites(){
		$favorites = UserFavorite::with(array('product','sizeer' => function($query){
			$query->where('quantity', '>', '0');
		},'colorer'=>function($query){
			$query->where('quantity', '>', '0');
		}))-> where('user_id','=',Auth::id())->paginate(50);
		$content = $this->makeView('front.user.favorite-list');
		$this->layout->content = $content;
		
		$content->with('favorites',$favorites);
	}
	
	public function deleteUserFavorite(){
		$id = Input::get('id',0);
		if (empty($id)){
			return Response::json(array('success'=>false));
		}
		UserFavorite::destroy($id);
		return Response::json(array('success'=>true));
	}
}

?>